package com.zhaojonhy.zhaopangwb.Fragment;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.StatusesAPI;
import com.zhaojonhy.zhaopangwb.R;
import com.zhaojonhy.zhaopangwb.adapter.StatusAdapter;
import com.zhaojonhy.zhaopangwb.bean.Statuses;
import com.zhaojonhy.zhaopangwb.bean.StatusesFriendsTimeline;
import com.zhaojonhy.zhaopangwb.bean.User;
import com.zhaojonhy.zhaopangwb.ui.UserInfoActivity;
import com.zhaojonhy.zhaopangwb.utils.AccessTokenKeeper;
import com.zhaojonhy.zhaopangwb.utils.BaseApplication;
import com.zhaojonhy.zhaopangwb.utils.Constants;
import com.zhaojonhy.zhaopangwb.widget.Pull2RefreshListView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/9.
 */

public class InfoFragmentStatuse extends BaseInfoFragment {

    final static String TAG = InfoFragmentStatuse.class.getSimpleName() ;

    private View view ;

    private Oauth2AccessToken mAccessToken;
    private StatusesAPI statusesAPI ;
    private BaseApplication application ;
    private User user;

    private Pull2RefreshListView plv_user_info;
    private View footView;
    // 个人微博列表
    private List<Statuses> statuses = new ArrayList<Statuses>();
    private StatusAdapter statusAdapter;
    // 显示当前已加载至的页数
    private int curPage = 1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (view == null)
        {
            view = View.inflate(mUserInfoActivity, R.layout.frag_info_statuse,null) ;
        }
        // 缓存的rootView需要判断是否已经被加过parent，如果有parent需要从parent删除，要不然会发生这个view已经有parent的错误。
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null)
        {
            parent.removeView(view);
        }

        mAccessToken = AccessTokenKeeper.readAccessToken(mUserInfoActivity) ;
        statusesAPI = new StatusesAPI(mUserInfoActivity, Constants.APP_KEY, mAccessToken) ;


        application = (BaseApplication) mUserInfoActivity.getApplication();
        user = application.currentUser ;

        initListView() ;
        loadStatuses(1) ;

        return view;
    }

    private void initLoadingLayout() {
        ILoadingLayout loadingLayout = plv_user_info.getLoadingLayoutProxy() ; // 下拉刷新的样式
        loadingLayout.setPullLabel(""); // 下拉时候的文字
        loadingLayout.setRefreshingLabel(""); //  正在刷新时候的文字
        loadingLayout.setReleaseLabel(""); // 释放后的文字
        loadingLayout.setLoadingDrawable(new ColorDrawable(getResources().getColor(R.color.transparent)));
    }

    private void initListView(){
        plv_user_info = (Pull2RefreshListView)view.findViewById(R.id.plv_user_info) ;
        initLoadingLayout();
        footView = View.inflate(mUserInfoActivity, R.layout.footview_loading , null) ;
        // addHeadView 是listView里面的方法，所以必须转成listView
        statusAdapter = new StatusAdapter(mUserInfoActivity, statuses);
        plv_user_info.setAdapter(statusAdapter);
        plv_user_info.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loadStatuses(1) ;
            }
        });
        plv_user_info.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                loadStatuses(curPage+1) ;
            }
        });

    }



    private void loadStatuses(final int requestPage) {
        if( user != null){
            Log.d(TAG,"user.getId()-->"+"user.getId(): "+user.getId());
            Log.d(TAG,"user.getId()-->"+"userName: "+user.getName());
        }

        statusesAPI.userTimeline(user == null ? -1 : user.getId(),
                "",
                0, 0, 50, requestPage, false, 0, false,
                new RequestListener() {
                    @Override
                    public void onComplete(String response) {
                        Log.d(TAG,"user.getId()-->"+"response: "+response);
                        Log.d(TAG,"userTimeline.getTotal_number():"+"loadStatuses1: "+
                                new Gson().fromJson(response,StatusesFriendsTimeline.class).getStatuses());
                        if( requestPage == 1 ){
                            statuses.clear();
                        }
                        curPage = requestPage ; //把加载页赋值给当前页

                        addStatus(new Gson().fromJson(response,StatusesFriendsTimeline.class)) ;
                        Log.d(TAG,"userTimeline.getTotal_number():"+"loadStatuses2: "+
                                new Gson().fromJson(response,StatusesFriendsTimeline.class).getStatuses());
                    }

                    @Override
                    public void onWeiboException(WeiboException e) {
                        Log.d(TAG,"user.getId()-->"+"response: "+"faile");
                        Log.d(TAG,"user.getId()-->"+"response: "+e.getMessage());
                    }
                });
    }

    private void addStatus(StatusesFriendsTimeline userTimeline){ //添加数据
        Log.d("调用了吗？？","addData") ;
        for (Statuses status : userTimeline.getStatuses()){
            Log.d(TAG,"status:"+status.getId()) ;
            //接口 List<E>containsboolean contains(Object o)如果列表包含指定的元素，则返回 true。
            // 更确切地讲，当且仅当列表包含满足 (o==null ? e==null : o.equals(e)) 的元素 e 时才返回 true。
            if( !statuses.contains(status)){ //list.contains(Bean) ,防止数据的重复添加
                Log.d(TAG,"is statuses.contains(status):"+"yes") ;
                statuses.add(status) ; //数据添加到集合中
            }else {
                Log.d(TAG,"is statuses.contains(status):"+"No") ;
            }
        }
        Log.d(TAG,"statuses in add:" + statuses.size() ) ;
        //可能要开线程
        statusAdapter.notifyDataSetChanged();//适配器更新
        plv_user_info.onRefreshComplete();
        Log.d(TAG,"statuses in add2:" + statuses.size() ) ;
        Log.d(TAG,"statusAdapter"+" in add:"+statusAdapter.getCount() ) ;

        Log.d(TAG,"userTimeline.getTotal_number():"+userTimeline.getTotal_number()) ;
        if (curPage < userTimeline.getTotal_number()) { //判断是否继续加载 ,当前页小于总页数
            addFootView(plv_user_info, footView) ; //继续加载
        }else {
            removeFootView(plv_user_info, footView) ; //移除加载
        }
    }

    private void addFootView(PullToRefreshListView plvHome, View footView ) {
        ListView lv = plvHome.getRefreshableView();
        if(lv.getFooterViewsCount() == 1) {
            lv.addFooterView(footView);
        }
    }

    private void removeFootView(PullToRefreshListView plvHome, View footView) {
        ListView lv = plvHome.getRefreshableView();
        Log.d(TAG,"lv.getFooterViewsCount()"+ lv.getFooterViewsCount()) ;
        if(lv.getFooterViewsCount() > 1) {
            lv.removeFooterView(footView);
        }
    }

}
